const CharacterModel = require('../dataBase/character');
const { formatPagination } = require('../utils/pagination');

module.exports = {
  async createCharacter(req, res, next) {
    try {
      const {
        name,
        image_url,
        description,
        background,
        preferences,
        extra_info
      } = req.body;

      const result = await CharacterModel.create({
        author_id: req.auth.user_id,  // 确保从认证中间件获取用户ID
        name,
        image_url,
        description,
        background,
        preferences,
        extra_info
      });

      res.status(201).json({ id: result.id });
    } catch (error) {
      console.error('Create Character Error:', error);  // 添加错误日志
      next(new Error('角色创建失败: ' + error.message));
    }
  },

  async getCharacter(req, res, next) {
    try {
      const character = await CharacterModel.getById(req.params.id);
      if (!character) {
        return res.status(404).json({ error: 'Character not found' });
      }
      res.json(character);
    } catch (error) {
      next(error);
    }
  },

  async listCharacters(req, res, next) {
    try {
      // 从查询参数解析（保留原始cursor类型，模型层处理类型转换）
      const { cursor, page_size = '10', my_characters = false } = req.query;
      // 处理分页大小（包含NaN保护）
      const pageSize = Math.min(
        parseInt(page_size, 10) || 10, // 默认10
        100 // 最大100
      );

      if (my_characters) {
        // 如果my_characters为true，则只返回当前用户的角色
        const result = await CharacterModel.listByCursor(cursor, pageSize, req.auth.user_id);
        res.json({
          code: 200,
          data: result
        });
      }
      else {
        // 调用模型层（直接透传cursor字符串）
        const result = await CharacterModel.listByCursor(cursor, pageSize);
        // 成功响应（结构完全由模型层决定）
        res.json({
          code: 200,
          data: result
        });
      }


    } catch (error) {
      console.error('角色分页失败:', error);

      // 带错误类型的响应（根据业务需要展示）
      res.status(500).json({
        code: 500,
        message: error.message.includes('数据库')
          ? '数据库查询异常'
          : '分页服务不可用'
      });
    }
  },

  async updateCharacter(req, res, next) {
    try {
      const affectedRows = await CharacterModel.updateById(
        req.params.id,
        req.body
      );

      if (affectedRows === 0) {
        return res.status(404).json({ error: 'Character not found' });
      }
      res.json({ message: 'Character updated successfully' });
    } catch (error) {
      next(error);
    }
  },

  async deleteCharacter(req, res, next) {
    try {
      const affectedRows = await CharacterModel.deleteById(req.params.id);
      if (affectedRows === 0) {
        return res.status(404).json({ error: 'Character not found' });
      }
      res.status(204).end();
    } catch (error) {
      next(error);
    }
  }
};